﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Globalization;
using Tihnut.Web.Timer;
using System.Diagnostics;
//using Pop3;
using System.Collections;
using OpenPOP.POP3;
using OpenPOP.MIMEParser;
using System.Text.RegularExpressions;

namespace SurveySystem.Core
{
    class EmailPollingAgent : PollingAgent
    {
        private string passwd = ConfigurationManager.AppSettings["Pop3Password"];
        private string username = ConfigurationManager.AppSettings["Pop3UserName"];
        private string host = ConfigurationManager.AppSettings["Pop3Address"];
        private int port = Convert.ToInt32(ConfigurationManager.AppSettings["Pop3Port"]);

        public EmailPollingAgent() : base("EmailPollingInterval") { }

        protected override void Poll()
        {
            POPClient popClient=new POPClient();
            try
            {
                popClient.Connect(host, port, true);
                popClient.Authenticate(username, passwd);

                for (int i = 1; i <= popClient.GetMessageCount(); i++)
                {
                    Message m = popClient.GetMessage(i, false);
                    string body = Regex.Replace((string)m.MessageBody[m.MessageBody.Count-1], @"<(.|\n)*?>", string.Empty);
                    CommunicationUtils.HandleNewEmail(m.FromEmail, m.Subject, body);
                }
                if (!popClient.DeleteAllMessages())
                    Debug.Print("A törlés szar");
                popClient.Disconnect();
            }
            catch (Exception ex)
            {
                Debug.Print("POPClient error:");
                Debug.Print(ex.Message);
                Debug.Print(ex.StackTrace);
                throw ex;
            }
        }
    }
}
